package gl.android.biyiqing.fragment;

import gl.API;
import gl.App;
import gl.android.biyiqing.R;
import gl.android.biyiqing.competent.AlbumControlBYQ;
import gl.anima.PotinToCover;
import gl.common.AjaxCallBackProxy;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.func.updoladPicture.SelectPictureActivity;
import gl.uitls.AndroidUtil;
import gl.uitls.Lg;
import gl.widget.AlbumControl;
import gl.widget.GridLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import de.greenrobot.event.EventBus;

public class AlbumFragment extends BaseFragment {
	// Content View Elements

	// Content View Elements

	private ImageView coverView;
	private OnClickListener toCoverView = new OnClickListener() {
		PotinToCover mPotinToCover = new PotinToCover();

		@Override
		public void onClick(View v) {

			if (v.getTag() == null || TextUtils.isEmpty(v.getTag().toString())) {
				SelectPictureActivity.pickImage(getActivity(),
						SelectPictureActivity.REQUESTCODE_TAKE_ALBUM);
			}
			else {
				ImageView cover = (ImageView) getActivity().getWindow()
						.getDecorView().findViewWithTag("COVNER");
				if (cover == null) {
					FrameLayout window = (FrameLayout) getActivity()
							.getWindow().getDecorView();
					cover = new ImageView(getActivity());
					FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
							FrameLayout.LayoutParams.MATCH_PARENT,
							FrameLayout.LayoutParams.MATCH_PARENT);
					params.gravity = Gravity.CENTER;
					cover.setLayoutParams(params);
					cover.setTag("COVNER");
					window.addView(cover);
				}
				try {
					Bitmap thumb = drawableToBitmap(((ImageView) v)
							.getDrawable());
					if (thumb != null) {
						cover.setImageBitmap(thumb);
						App.mFBitmap.configLoadingImage(thumb);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				mPotinToCover.zoomImageFromThumb((ViewGroup) getActivity()
						.getWindow().getDecorView(), v, cover,
						R.drawable.image_18);
				App.mFBitmap.display(cover, v.getTag().toString());
			}

		}
	};
	private OnLongClickListener delLongPressLisen = new OnLongClickListener() {

		@Override
		public boolean onLongClick(final View v) {

			if (v.getTag() == null || TextUtils.isEmpty(v.getTag().toString())) {
				return false;
			}
			else {
				// http://121.41.26.194:8080/by_webservice/DeletePhotoList?photoid=1,2
				AndroidUtil.genDialog(v.getContext(), "确定要删除?", "删除相册图片",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
//								Tip.show("删除图片" + url);
								gridlayout.removeView(v);
								deleImage(v.getTag(R.id.img).toString());
							}

						});
				return true;
			}
		}

	};

	private void deleImage(String photoid) {
		BaseControl.get(API.URL + "DeletePhotoList?photoid=%s",
				new AjaxCallBackProxy() {
					@Override
					public void onSuccess(String t) {
						if (!isValueFragment()) {
							return;
						}
						super.onSuccess(t);
						try {
							if (new JSONObject(t).getJSONArray("data") == null) {
								return;
							}
						} catch (Exception e) {
							e.printStackTrace();
							onFailure(e, 0, e.getMessage());
						}
					}
				}, photoid);
	}

	private GridLayout gridlayout;
	private ViewGroup container;
	private AlbumControl mAlbumGirdLayoutControl;
	private ScrollView scrollView1;
	private boolean isAddAble;

	// End Of Content View Elements

	private void bindViews() {
		container = (ViewGroup) findViewById(R.id.container);
		gridlayout = (GridLayout) findViewById(R.id.gridlayout);
		scrollView1 = (ScrollView) findViewById(R.id.scrollView1);
		coverView = (ImageView) findViewById(R.id.imageView1);
	}

	public AlbumFragment() {
	}

	public void onEvent(RefreshAlbum mRefreshAlbum) {
		Lg.i("mRefreshAlbum");
		if (mRefreshAlbum.getUserid() == userID) {
			initData();
		}

	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		EventBus.getDefault().unregister(this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.albumthum, container, false);

		isAddAble = UserManger.getInstance().userid.equals(userID) ? true
				: false;
		bindViews();
		mAlbumGirdLayoutControl = new AlbumControlBYQ(gridlayout);
		initData();
		EventBus.getDefault().register(this);

		return rootView;
	}

	private void initData() {
		if (data == null) {
			return;
		}
		JSONArray jo;
		try {
			jo = new JSONArray(data);
			mAlbumGirdLayoutControl.removeAll();
			for (int i = 0; i < jo.length(); i++) {
				mAlbumGirdLayoutControl.addViewToGrid(
						API.IMAGEURL
								+ jo.getJSONObject(i).getString("thumbfiles"),
						API.IMAGEURL
								+ jo.getJSONObject(i).getString("uploadfiles"),jo.getJSONObject(i).opt("photoid"),
						toCoverView, delLongPressLisen);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} finally {
			// add button for add photo
			if (isAddAble) {
				mAlbumGirdLayoutControl.addViewToGrid("", "", 0,toCoverView,
						delLongPressLisen);
			}
		}

	}

	public static Bitmap drawableToBitmap(Drawable drawable) {
		if (drawable instanceof BitmapDrawable) {
			return ((BitmapDrawable) drawable).getBitmap();
		}

		int width = drawable.getIntrinsicWidth();
		width = width > 0 ? width : 1;
		int height = drawable.getIntrinsicHeight();
		height = height > 0 ? height : 1;

		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
		drawable.draw(canvas);

		return bitmap;
	}

	public void refresh(Object userphoto) {
		if (userphoto == null) {
			return;
		}
		int currentScrollY = scrollView1.getScrollY();
		data = userphoto.toString();
		initData();
		scrollView1.scrollTo(0, currentScrollY);
	}
}
